package cj.web.marry.controllers;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.utils.Page;
import cj.utils.ReturnUUID;
import cj.utils.weixin.HttpsWenXinUtil;
import cj.web.BaseController;
import cj.web.mall.dao.UserDAO;
import cj.web.marry.constants.MemberComTypeEnum;
import cj.web.marry.dao.CmpActDAO;

@Path("cmpAct")
public class CmpActController extends BaseController{

	protected static final Log logger = LogFactory.getLog(CmpActController.class); 
	
	@Autowired
	private CmpActDAO cmpActDAO;
	
	@Autowired
	private UserDAO userDao;
	
	@Get("homeCode")  //活动页面Code
	public String homeCode(Model model,@Param("code")String code, HttpServletResponse response) throws Exception{
		Map oauth2Reps = HttpsWenXinUtil.retOauth2Infor(code, Constants.weixinkey.AppID, Constants.weixinkey.AppSecret);
		String openId = oauth2Reps.get("openid").toString();
		
//		String access_token = "5_t_0b1DfJd-miqaupR01BIoZkDZBL_FAVKk4TUW3_HTf9MQzfBzWD6tcJNVO0DSdSBmLDWVHckSPoQJOHq8xr9Q";
//		String openId = "ofwuNsyVHbXdpotCwZ_ZJLp7DSrQ";
		setCookie(response, "openId", openId);
		return "r:home";
	}
	
	@Get("home")  //活动页面
	public String home(Model model, HttpServletRequest request) throws Exception{
		
		Map<String, String> config = getConfigSign(request);
		model.add("Config",config);
		
		model.add("Title", "长江婚典商城-您的专属婚品");
		model.add("Desc", "只为您专属打造");
		model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/homeCode"+oauth_end);
		return "/views/marry/meet/cmpActivity/metroCorner.vm";
	}
	
	@Get("cmpActPage")  //活动页面
	public String cmpActPage(Model model, HttpServletRequest request) throws Exception{
		
		if( isLogin(request) ){
			
			String phone = getCookieValueByName(request, "phone");
			int buyerId = userDao.getBuyerId(phone);
			int isExist = userDao.isExistMemberDetailCmp(buyerId,MemberComTypeEnum.NUM_1.getValue());
			
			if(isExist==0){
				return "r:../xqLoginCmp/fail";
			}
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			
			model.add("Title", "长江婚典商城-您的专属婚品");
			model.add("Desc", "只为您专属打造");
			model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/homeCode"+oauth_end);
		}else{
			String retPg = URLEncoder.encode("cmpAct/cmpActPage", "utf-8");
			return "r:../xqLoginCmp/login?returnPage=" + retPg;
		}
		
		return "/views/marry/meet/cmpActivity/latestActivity.vm";
	}
	
	
	@Get("getList")  //活动列表方法
	public String home(@Param("start") int start,@Param("length") int length,
			Model model, HttpServletRequest request) throws Exception{
		
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		List<Map> gamels = cmpActDAO.queryAllForEndDate(start*length,length);
		
		int totalCount = cmpActDAO.queryAllForEndDateSize();
		//分页计算
		Page p= new Page<Map>(0, length, gamels, totalCount);
		jo.put("list", gamels);
		jo.put("repsize", p.getTotalPages());
		jo.put("totalCount", totalCount);
		
		return "@"+jo.toString();
	}
	
	@Get("detailCode")  //活动详情Code
	public String detailCode(Model model,@Param("code")String code, @Param("state")int gameId, HttpServletResponse response){
		String openId = HttpsWenXinUtil.retOpenId(code,Constants.weixinkey.AppID, Constants.weixinkey.AppSecret);
		setCookie(response, "openId", openId);
		return "r:detail?gameId=" + gameId;
	}
	
	/**
	 * 活动详情
	 * @param model
	 * @param gameId	活动ID
	 * @return
	 * @throws Exception 
	 */
	@Get("detail")
	public String detail(Model model,@Param("gameId")int gameId, HttpServletRequest request) throws Exception{
		List<Map> obj = cmpActDAO.queryById(gameId);
		if(obj!=null && obj.size()>0){
			String endDate = obj.get(0).get("endDate").toString();
			int flagendDate = DateUtils.compareDateWithNow(DateUtils.parse(endDate));
			if(flagendDate>=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			String startDate = obj.get(0).get("startDate").toString();
			int flagstartDate = DateUtils.compareDateWithNow(DateUtils.parse(startDate));
			if(flagstartDate<=0){
				model.add("flag", true);
			}else{
				model.add("flag", false);
			}
			
			obj.get(0).put("startDate", DateUtils.getMinusTime(obj.get(0).get("startDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			obj.get(0).put("endDate", DateUtils.getMinusTime(obj.get(0).get("endDate").toString(), DateUtils.DATE_SMALL_STR, 0));
			model.add("obj", obj.get(0));
			
			Map<String, String> config = getConfigSign(request);
			model.add("Config",config);
			String gameName = obj.get(0).get("name").toString();
			model.add("Title", gameName);
			model.add("Desc", gameName);
			model.add("LinkURL", oauth_start+request.getScheme() +"://" + request.getServerName() + "/pubAct/detailCode"+oauth_end);
		}
		
		return "/views/marry/meet/cmpActivity/activityDetail.vm";
	}
	
	@Get("joinPubAct")  //参加活动
	public synchronized String detailCode(Model model,@Param("gameId")int gameId,HttpServletRequest request) throws Exception{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			if( isLogin(request) ){
				String phone = getCookieValueByName(request, "phone");
				int buyerId = userDao.getBuyerId(phone);
				
				int count = cmpActDAO.queryCmpActivityOrderCount(buyerId, gameId);
				if(count==0){
					String orderNo = ReturnUUID.getOrderNo("");
					List<Map> obj = cmpActDAO.queryById(gameId);
					cmpActDAO.createCmpActOrder(gameId, orderNo, buyerId, 
							obj.get(0).get("duration").toString(), obj.get(0).get("price").toString(), phone);
					
					cmpActDAO.updateCmpActivity(gameId);
				}else{
					jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
				}
				
			}else{
				String retPg = URLEncoder.encode("cmpAct/detail?gameId=" + gameId, "utf-8");
				jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
				jo.put("returnPage", "../xqLoginCmp/login?returnPage=" + retPg);
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
}
